using System;
using System.Net.Http;
using System.Net.Http.Headers;

namespace ERP_SaaS_WinForm.登录.Common
{
	/// <summary>
	/// Provides a single reusable HttpClient and manages attaching the JWT token.
	/// </summary>
	public static class HttpClientProvider
	{
		private static readonly HttpClient sharedHttpClient = new HttpClient();

		/// <summary>
		/// Gets the shared HttpClient instance. Prefer using this for all API calls.
		/// </summary>
		public static HttpClient Client => sharedHttpClient;

		/// <summary>
		/// Optionally set a base address for all requests.
		/// </summary>
		public static void SetBaseAddress(string baseUrl)
		{
			if (!string.IsNullOrWhiteSpace(baseUrl))
			{
				sharedHttpClient.BaseAddress = new Uri(baseUrl);
			}
		}

		/// <summary>
		/// Set or clear the Authorization header using a JWT token.
		/// </summary>
		public static void SetJwtToken(string jwtToken)
		{
			sharedHttpClient.DefaultRequestHeaders.Authorization = null;
			if (!string.IsNullOrWhiteSpace(jwtToken))
			{
				sharedHttpClient.DefaultRequestHeaders.Authorization =
					new AuthenticationHeaderValue("Bearer", jwtToken);
			}
		}
	}
}

